package util;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ClassUtils;
import org.springframework.util.PathMatcher;
import springfox.documentation.RequestHandler;

/**
 * 接口测试文档工具类
 * @author tianbl
 * @date 2019/5/23
 */
public class SwaggerUtil {
    private static PathMatcher pathMatcher = new AntPathMatcher(".");

    /**
     * Predicate ant match package
     *
     * @param basePackage - base package of the classes
     * @return this
     */
    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage))
            .or(true);
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

    private static Function<Class<?>, Boolean> handlerPackage(String basePackage) {
        return input -> pathMatcher.match(basePackage,
            ClassUtils.getPackageName(input));
    }
}
